const request = require('request');
const OSS = require('ali-oss');
const fs =  require('fs');

var client = new OSS({
  region: 'oss-cn-beijing',
  accessKeyId: 'LTAI4Ft83grBFLEKNE97PSYn',
  accessKeySecret: 'uO9v0fxwx8lvSCK8JswURWEKHGCAn3',
  bucket: 'nodemall',
  endPoint: 'oss-cn-beijing.aliyuncs.com'
});
var ali_oss = {
  bucket: 'nodemall',
  endPoint: 'oss-cn-beijing.aliyuncs.com'
};

async function PutOssStream(url) {
  try {
    // 要创建的文件名
    var filename = Date.now() + '.jpg';
    // 本地缓存的文件名
    var localFile = filename;
    // 创建写入缓存文件流
    var stream = fs.createWriteStream(localFile);
    stream.on('finish', async () => {
      // 完成本地缓存流的写入，处理上传到OSS
      var key = 'file/' + localFile;
      client.useBucket(ali_oss.bucket);
      // 创建读取缓存的文件流
      let stream = fs.createReadStream(localFile);
      let result = await client.putStream(key, stream);
      var imageSrc = result.name;
      // 完成上传后删除缓存文件
      fs.unlinkSync('./' + localFile);
      var resultUrl = result.res.requestUrls[0];
      console.log(resultUrl);
    });
    // 流管道
    request(url).pipe(stream);
  } catch (e) {
    lonsole.error(e);
  }
}

var url = 'https://www.baidu.com/img/baidu_jgylogo3.gif';
var a = PutOssStream(url);
